/**
 * Project: arild.toolkit
 * 
 * File Created at 2015年10月26日
 * $Id$
 * 
 * Copyright 2015 dface.cn Croporation Limited.
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of
 * dface Company. ("Confidential Information").  You shall not
 * disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license agreement you entered into
 * with www.dface.cn
 */
package cn.dface.ameba.toolkit.util;

import javax.servlet.http.HttpServletRequest;

import org.springframework.util.StringUtils;

/**
 * RequestUtils
 * 
 * @author a1
 */
public class RequestUtils {
    private static String ACCEPT      = "accept";
    private static String JSON_FORMAT = "application/json";
    private static String XML_HEADER  = "X-Requested-With";
    private static String XML_REQUEST = "XMLHttpRequest";

    /**
     * 判断是否是ajax异步请求
     * 
     * @param request
     * @return
     */
    public static boolean isAjaxRequest(HttpServletRequest request) {
        String header = request.getHeader(ACCEPT);
        String xmlHeader = request.getHeader(XML_HEADER);
        return ((null != header && header.indexOf(JSON_FORMAT) > -1)
                || (null != xmlHeader && xmlHeader.indexOf(XML_REQUEST) > -1));
    }

    /**
     * 获取异步请求json错误信息
     * 
     * @param msg
     * @return
     */
    public static String getResponseErrorJson(String msg) {
        return "[{\"status\":\"error\",\"errorMsg\":\"" + msg + "\"}]";
    }

    /**
     * 获取上下文
     * 
     * @param request
     * @return
     */
    public static String findContextPath(HttpServletRequest request) {
        String contextPath = request.getContextPath();

        if (!StringUtils.endsWithIgnoreCase(contextPath, "/")) {
            contextPath = contextPath + "/";
        }
        return contextPath;
    }

    /**
     * @param request
     * @return
     */
    public static String findDomain(HttpServletRequest request) {
        String url = request.getRequestURL().toString();
        String uri = request.getRequestURI();
        String domain = url;
        if (StringUtils.hasText(uri)) {
            int index = url.indexOf(uri);
            if (-1 != index) {
                domain = url.substring(0, index);
            }
        }
        //去掉端口
        int port = domain.lastIndexOf(":");
        if (-1 != port) {
            domain = domain.substring(0, port);
        }
        return domain;
    }

}
